<template>
    <div class="dialog_header draggable" @mousedown.stop="onMouseDown">
        <div class="name">{{data.data.name}}</div>
        <div style="display: flex; align-items: center">
            <img src="@/assets/monitor/del.png" style="width: 16px; height: 16px; cursor: pointer"
                @click.stop="data.show = false" alt="" />
        </div>
    </div>
</template>

<script setup>
const { monitorStore, monitorState } = inject('MonitorStore')
const props = defineProps({
    data: Object,
    dataindex: Number
})

const onMouseDown = event => {
    monitorStore.clickMatchDialog(props.data)
    props.data.dragging = true
    // 计算鼠标相对于 div 左上角的偏移量
    props.data.offsetX = event.clientX - props.data.position.x
    props.data.offsetY = event.clientY - props.data.position.y
    // 禁止浏览器选择文本（提高拖拽体验）
    document.body.style.userSelect = 'none'
    // 绑定鼠标移动和鼠标松开事件
    document.addEventListener('mousemove', onMouseMove)
    document.addEventListener('mouseup', onMouseUp)
}

const onMouseMove = event => {
    if (props.data.dragging) {
        // 更新 div 的位置
        props.data.position.x = event.clientX - props.data.offsetX
        props.data.position.y = event.clientY - props.data.offsetY
        let newX = event.clientX - props.data.offsetX
        let newY = event.clientY - props.data.offsetY

        // 获取窗口的宽度和高度
        const maxX = window.innerWidth - props.data.ref.clientWidth
        const maxY = window.innerHeight - props.data.ref.clientHeight

        // 限制拖动范围
        newX = Math.max(0, Math.min(newX, maxX))
        newY = Math.max(0, Math.min(newY, maxY))

        props.data.position.x = newX
        props.data.position.y = newY
    }
}

// 鼠标松开事件
const onMouseUp = () => {
    props.data.dragging = false
    document.removeEventListener('mousemove', props.data.onMouseMove)
    document.removeEventListener('mouseup', props.data.onMouseUp)
    // 恢复浏览器文本选择功能
    document.body.style.userSelect = ''
}
</script>

<style lang="scss" scoped>
.dialog_header {
    display: flex;
    height: 40px;
    min-height: 40px;
    padding: 0 12px;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    // border-bottom: 1px solid #ebebeb;
    background-color: #f8f9fa;

    .name {
        font-size: 16px;
        font-weight: bold;
        color: #000;
    }
}

.draggable {
    cursor: grab;
    /* 设置鼠标为抓取手形 */
}

.draggable:active {
    cursor: grabbing;
    /* 拖拽时鼠标变成抓取状态 */
}
</style>
